package com.robot.member.controller;

import com.robot.member.pojo.Address;
import com.robot.member.service.AddressService;
import com.robot.member.service.MemberService;
import entity.PageResult;
import entity.Result;
import entity.StatusCode;
import io.jsonwebtoken.Claims;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;
import util.CheckUtil;
import util.UpdateUtil;

import javax.servlet.http.HttpServletRequest;

/**
 * address控制器层
 *
 * @author lin
 */
@RestController
@CrossOrigin
@RequestMapping("/address")
public class AddressController {
    @Autowired
    private AddressService addressService;
    @Autowired
    private MemberService memberService;

    @Autowired
    private CheckUtil checkUtil;

    @Autowired
    private HttpServletRequest request;

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Value("${sys.memberAddressCount}")
    private int sysMemberAddressCount;
    /**
     * address表sex 性别 0-女 1-男 2-未知
     */
    private final String female = "0";
    private final String male = "1";
    private final String secrecy = "2";


    /**
     * 会员查看地址列表
     *
     * @param page
     * @param size
     * @return
     */
    @RequestMapping(value = "/{page}/{size}", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    public Result findAllByMemberIdAndDeletedAtIsNullOrderByCreatedAtDesc(@PathVariable int page, @PathVariable int size) {
        Claims claims = (Claims) request.getAttribute("robot_member");
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("claims.getId()=" + claims.getId());
        //前端调用findByToken接口检查过了,所以这里不再对会员是否存在和状态进行判断

        Page<Address> pageData = addressService.findAllByMemberIdAndDeletedAtIsNullOrderByCreatedAtDesc(claims.getId(), page, size);
        return new Result(StatusCode.SUCCESS_QUERY, new PageResult<>(pageData.getTotalElements(), pageData.getContent()));
    }

    /**
     * 会员查看地址详情
     *
     * @param id ID
     * @return
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public Result findById(@PathVariable String id) {
        Claims claims = (Claims) request.getAttribute("robot_member");
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("claims.getId()=" + claims.getId());
        //前端调用findByToken接口检查过了,所以这里不再对会员是否存在和状态进行判断

        Address addressInDb = addressService.findByIdAndMemberId(id, claims.getId());
        logger.info("addressInDb=" + addressInDb);
        if (addressInDb == null || addressInDb.getDeletedAt() != null) {
            return new Result(StatusCode.ERROR_RECORD_DOES_NOTE_EXIST);
        }
        return new Result(StatusCode.SUCCESS_QUERY, addressInDb);
    }

    /**
     * 会员增加地址详情
     *
     * @param address
     */
    @RequestMapping(value = "", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public Result add(@RequestBody Address address) {
        Claims claims = (Claims) request.getAttribute("robot_member");
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("claims.getId()=" + claims.getId());
        //前端调用findByToken接口检查过了,所以这里不再对会员是否存在和状态进行判断

        logger.info("address=" + address);
        Page<Address> pageData = addressService.findAllByMemberIdAndDeletedAtIsNullOrderByCreatedAtDesc(claims.getId(), 1, 10);
        logger.info("pageData=" + pageData);
        if (pageData.getTotalElements() >= sysMemberAddressCount) {
            return new Result(StatusCode.ERROR_ADDRESS_COUNT_INVALID);
        }

        if (address.getRecipientName() == null || "".equals(address.getRecipientName())) {
            return new Result(StatusCode.ERROR_RECIPIENT_NAME_REQUIRED);
        }
        if (address.getSex() == null || "".equals(address.getSex())) {
            return new Result(StatusCode.ERROR_SEX_REQUIRED);
        } else {
            if (!female.equals(address.getSex()) && !male.equals(address.getSex()) && !secrecy.equals(address.getSex())) {
                return new Result(StatusCode.ERROR_SEX_INVALID);
            }
        }
        if (address.getPhone() == null || "".equals(address.getPhone())) {
            return new Result(StatusCode.ERROR_PHONE_REQUIRED);
        } else if (!checkUtil.checkPhone(address.getPhone())) {
            return new Result(StatusCode.ERROR_INVALID_PHONE);
        }
        if (address.getProvinceId() == null || "".equals(address.getProvinceId())) {
            return new Result(StatusCode.ERROR_PROVINCE_ID_REQUIRED);
        }
        if (address.getProvince() == null || "".equals(address.getProvince())) {
            return new Result(StatusCode.ERROR_PROVINCE_REQUIRED);
        }
        if (address.getCityId() == null || "".equals(address.getCityId())) {
            return new Result(StatusCode.ERROR_CITY_ID_REQUIRED);
        }
        if (address.getCity() == null || "".equals(address.getCity())) {
            return new Result(StatusCode.ERROR_CITY_REQUIRED);
        }
        if (address.getAreaId() == null || "".equals(address.getAreaId())) {
            return new Result(StatusCode.ERROR_AREA_ID_REQUIRED);
        }
        if (address.getArea() == null || "".equals(address.getArea())) {
            return new Result(StatusCode.ERROR_AREA_REQUIRED);
        }
        if (address.getAddress() == null || "".equals(address.getAddress())) {
            return new Result(StatusCode.ERROR_ADDRESS_REQUIRED);
        }
        if (address.getLongitude() == null || "".equals(address.getLongitude())) {
//            return new Result(StatusCode.ERROR_LONGITUDE_REQUIRED);
        }
        if (address.getLatitude() == null || "".equals(address.getLatitude())) {
//            return new Result(StatusCode.ERROR_LATITUDU_REQUIRED);
        }
        address.setMemberId(claims.getId());
        addressService.add(address);
        return new Result(StatusCode.SUCCESS_INSERTED);
    }

    /**
     * 会员修改地址详情
     *
     * @param address
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.PUT, produces = "application/json; charset=utf-8")
    public Result update(@RequestBody Address address, @PathVariable String id) {
        Claims claims = (Claims) request.getAttribute("robot_member");
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("claims.getId()=" + claims.getId());
        //前端调用findByToken接口检查过了,所以这里不再对会员是否存在和状态进行判断

        logger.info("address=" + address);
        Address addressInDb = addressService.findByIdAndMemberId(id, claims.getId());
        logger.info("addressInDb=" + addressInDb);
        if (addressInDb == null || addressInDb.getDeletedAt() != null) {
            return new Result(StatusCode.ERROR_RECORD_DOES_NOTE_EXIST);
        }
        if (address.getPhone() != null && !"".equals(address.getPhone())) {
            if (!checkUtil.checkPhone(address.getPhone())) {
                return new Result(StatusCode.ERROR_INVALID_PHONE);
            }
        }
        if (address.getSex() != null && !"".equals(address.getSex())) {
            if (!female.equals(address.getSex()) && !male.equals(address.getSex()) && !secrecy.equals(address.getSex())) {
                return new Result(StatusCode.ERROR_SEX_INVALID);
            }
        }

        address.setCreatedAt(addressInDb.getCreatedAt());
        address.setMemberId(addressInDb.getMemberId());
        UpdateUtil.copyNonNullProperties(address, addressInDb);
        addressService.update(addressInDb);
        return new Result(StatusCode.SUCCESS_UPDATED);
    }

    /**
     * 会员删除地址详情
     *
     * @param id
     */
    @RequestMapping(value = "{id}", method = RequestMethod.DELETE, produces = "application/json; charset=utf-8")
    public Result delete(@PathVariable String id) {
        Claims claims = (Claims) request.getAttribute("robot_member");
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("claims.getId()=" + claims.getId());
        //前端调用findByToken接口检查过了,所以这里不再对会员是否存在和状态进行判断

        Address addressInDb = addressService.findByIdAndMemberId(id, claims.getId());
        if (addressInDb == null || addressInDb.getDeletedAt() != null) {
            return new Result(StatusCode.ERROR_RECORD_DOES_NOTE_EXIST);
        }
        addressService.deleteById(id);
        return new Result(StatusCode.SUCCESS_DELETED);
    }
}
